package org.gavin.core.conf;

import com.github.benmanes.caffeine.cache.Cache;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import lombok.RequiredArgsConstructor;
import org.gavin.core.attribute.YmlSafetyAttribute;
import org.gavin.core.domain.ExpireCache;
import org.gavin.core.service.limit.AccessLimitAbstract;
import org.gavin.core.service.limit.impl.LocalAccessLimit;
import org.gavin.core.service.safety.SafetyAbstract;
import org.gavin.core.service.safety.impl.YmlSafety;
import org.hibernate.validator.HibernateValidator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * BeanInit
 *
 * @author grl
 * @date 2024/1/4
 */
@Configuration
@RequiredArgsConstructor
public class BeanInitConfig {

    @Bean
    @ConditionalOnMissingBean(Validator.class)
    public Validator validator() {
        return Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory()
                .getValidator();
    }

    @Bean
    @ConditionalOnMissingBean(SafetyAbstract.class)
    public SafetyAbstract getSafety(YmlSafetyAttribute ymlSafetyAttribute, HttpServletRequest request) {
        return new YmlSafety(ymlSafetyAttribute, request);
    }

    @Bean
    @ConditionalOnMissingBean(AccessLimitAbstract.class)
    public AccessLimitAbstract getAccessLimit(@Qualifier(value = "accessLimitLocalCache") Cache<String, ? extends ExpireCache> cache) {
        return new LocalAccessLimit(cache);
    }
}
